<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['技术管理', '生产流程']" :currentMenu="jkeForm.title"></crumbs>
    <div class="form-body">
      <a-card title="基础信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="流程编号">
            <a-input
              v-decorator="[
                'flowCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入流程编号或自动生成',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('mess_product_flow', 'flow_code', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="请输入"
              :disabled="isEdit"
            />
            <span class="btn-text code-btn" v-if="!isEdit" @click="genEntityCode">自动生成</span>
          </a-form-item>
          <a-form-item label="流程名称">
            <a-input
              v-decorator="['flowName', { rules: [{ required: true, message: '请输入' }] }]"
              placeholder="请输入"
              :maxLength="30"
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-decorator="['status', { rules: [{ required: true, message: '请选择' }] }]"
              placeholder="请选择"
            >
              <a-select-option value="enable">启用</a-select-option>
              <a-select-option value="disable">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="流程工序" :bordered="false" style="margin-top: 12px">
        <j-editable-table
            ref="processTable"
            :loading="processTable.loading"
            :columns="processTable.columns"
            :dataSource="processTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :actionButton="true"
            @valueChange="valueChange"
          >
            <template v-slot:processCodeName="props">
              <a-input @click="openItProcess(props)" :value="props.value" placeholder="请选择" :read-only="true" :class="props.value? 'has-value' : ''">
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon slot="suffix" type="close-circle" theme="filled" class="close-icon" @click="getSelectValueProcess(false, '', [], props.rowId)" />
              </a-input>
            </template>
            <template v-slot:serialNo="props">
              <div style="text-align: center">{{ props.index + 1 }}</div>
            </template>
            <template v-slot:processRequire="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                :maxLength="500"
              />
            </template>
            <template v-slot:processWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'processWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:excessWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'excessWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:action="props">
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(props)"
              >
                <a style="padding-left: 3px;color:#F25643">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
      </a-card>
      <a-card title="应用物料分类" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="物料分类" style="width: 50%">
            <a-tree-select
              allow-clear
              v-decorator="['goodsCategory', { rules: [{ required: true, message: '请选择物料分类' }] }]"
              :multiple="false"
              placeholder="请选择"
              :tree-data="treeData"
              :replaceFields="replaceFields"
              :show-checked-strategy="SHOW_ALL"
              treeCheckStrictly
              search-placeholder="请选择"
              tree-checkable
               @change="treeChange"
            />
              <!-- treeCheckStrictly -->
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="其他" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" :maxLength="500" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <div class="footer-submit form-footer">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="handleSubmit"> 提交 </a-button>
    </div>
    <tableSelect ref="tableSelectProcess" @getSelectValue="getSelectValueProcess" :key="indexProcess">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterFormProcess">
            <a-form-model-item label="工序编号">
              <a-input v-model="filterFormProcess.processCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="工序名称">
              <a-input v-model="filterFormProcess.processName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchProcess()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetProcess">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { messProductFlowAdd, getDictModel, messProductFlowEdit, messProductFlowQueryById, categoryGetTree } from '@/api/goodsManagement'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { validateDuplicateValue, clearNoNum, fourFloatNum } from '@/utils/util'
import { TreeSelect } from 'ant-design-vue'
import tableSelect from '@/components/tableSelect'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
const SHOW_ALL = TreeSelect.SHOW_ALL
export default {
  name: 'workProcessForm', //新增生产流程
  data() {
    return {
      jkeForm: {
        title: '新建流程',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: messProductFlowAdd,
      isEdit: false,
      dictOptions: '', //报工单位
      mainDivWidth: 0,
      attachment: '', //附件
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      // 物料分类树形下拉配置---begin
      SHOW_PARENT,
      SHOW_ALL,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id',
      },
      treeData: [],
      // 物料分类树形下拉配置---end

      // editTable配置---begin
      processTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'serialNo',
            type: FormTypes.slot,
            slotName: 'serialNo',
            width: '80px',
          },
          {
            title: '工序id',
            key: 'processId',
            type: FormTypes.hidden,
          },
          {
            title: '工序',
            key: 'processCodeName',
            width: '20%',
            isrequired: true,
            type: FormTypes.slot,
            slotName: 'processCodeName',
          },
          {
            title: '报工单位',
            key: 'processWorkUnit',
            width: '18%',
            type: FormTypes.select,
            options: [],
            placeholder: '请选择',
            defaultValue: '',
            isrequired: true,
            validateRules: [
              { required: true, message: '${title}不能为空' },
            ],
          },
          {
            title: '报工配比',
            key: 'processWorkRate',
            width: '18%',
            isrequired: true,
            type: FormTypes.slot,
            placeholder: '请输入',
            defaultValue: '1',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}不能为空且必须大于0',
              },
            ],
          },
          {
            title: '超量报工（%）',
            key: 'excessWorkRate',
            width: '18%',
            type: FormTypes.slot,
            placeholder: '请输入',
            // disabled: true,
            defaultValue: '',
            validateRules: [
              { required: false, message: '${title}不能为空' },
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}必须大于0',
              },
            ],
          },
          {
            title: '工序要求',
            width: '18%',
            key: 'processRequire',
            type: FormTypes.slot,
            placeholder: '请输入',
            // disabled: true,
            defaultValue: '',
          },
          {
            title: '工序名称',
            key: 'processName',
            type: FormTypes.hidden,
          },
          {
            title: '操作',
            width: '8%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      // editTable配置---end
      // tableSelect配置---begin
      indexProcess: 0,
      processRowId: '',
      columnsProcess: [
        {
          title: '工序编号',
          dataIndex: 'processCode',
          width: 180,
          ellipsis: true,
        },
        {
          title: '工序名称',
          dataIndex: 'processName',
          key: 'processName',
          width: 180,
          ellipsis: true,
        },
        {
          title: '报工单位',
          dataIndex: 'processWorkUnitText',
          width: 180,
          key: 'processWorkUnitText',
          ellipsis: true,
        },
        {
          title: '工序要求',
          dataIndex: 'processRequire',
          width: 180,
          key: 'processRequire',
          ellipsis: true,
        },
      ],
      processValue: '',
      processText: '',
      filterFormProcess: {
        processCode: '', //工序编号
        processName: '', //工序名称
      },
      // tableSelect配置---end
    }
  },
  components: {
    FileUpload,
    crumbs,
    tableSelect
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    // edittable输入数字格式化
    inputNums(props, e, key, ref) {
      this.$refs[ref].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            [key]: clearNoNum(e.target.value),
          },
        },
      ])
    },
    // 选择流程工序事件-------begin
    // --搜索
    searchProcess() {
      this.$refs.tableSelectProcess.searchQuery(this.filterFormProcess)
    },
    // --重置
    searchResetProcess() {
      this.filterFormProcess.processCode = ''
      this.filterFormProcess.processName = ''
      this.$refs.tableSelectProcess.searchReset()
    },
    // --删除
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    // --打开选择弹窗
    openItProcess(props) {
      this.filterFormProcess = {
        processCode: '', //工序编号
        processName: '', //工序名称
      }
      this.processRowId = props.rowId
      let tableValue = this.$refs.processTable.getValuesSync({ validate: false, rowIds: [props.rowId] })
        .values[0]
      console.log(tableValue,'tableValuev');
      let par = {
        list: '/mess/messProductProcess/getDictPageList',
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: false, //是否多选
        columns: this.columnsProcess, //表格配置
        value: tableValue.processId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: tableValue.processName || '', //回显的中文，如：'张三'
        textKey: 'processName', //回显的中文key
      }
      this.$refs.tableSelectProcess.getInit(par)
    },
    // --选中回调
    getSelectValueProcess(id, text, item, rowId) {
      if (!id) {
        this.processValue = ''
        this.processText = ''
        this.$refs.processTable.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              processId: '',
            processCodeName: '',
            processWorkUnit: '',
            processRequire: '',
            excessWorkRate: '',
            processName: '',
            processWorkRate: '1'
            },
          },
        ])
        return
      }
      this.indexProcess += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.processValue = id
      this.processText = text
      this.onChangeSelect(item[0])
      console.log(id, text, item, '列表选择的数据')
    },
    // 工序 change
    onChangeSelect(obj) {
      console.log(this.processRowId, 'this.processRowId')
      let tableValue = this.$refs.processTable.getValuesSync({ validate: false }).values
      for (let i = 0; i < tableValue.length; i++) {
        const v = tableValue[i];
        if (v.processId == this.processValue) {
          this.$refs.processTable.removeRows(this.processRowId)
          this.$antdMessage.warning('该工序已存在，请直接修改数据')
          return
        }
      }
      this.$refs.processTable.setValues([
        {
          rowKey: this.processRowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            processId: this.processValue,
            processCodeName: `${obj.processCode}-${obj.processName} `,
            processWorkUnit: obj.processWorkUnit || '',
            processRequire: obj.processRequire || '',
            excessWorkRate: obj.excessWorkRate,
            processName: obj.processName,
            processWorkRate: '1'
          },
        },
      ])
      const { error, values } = this.$refs.processTable.getValuesSync({ validate: true })
      console.log(values, 'valuesvaluesvalues')
    },
    valueChange(type) {
      if (type.column.key == 'processWorkRate') {
        if (type.value) {
          this.$refs.processTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                processWorkRate: fourFloatNum(type.value),
              },
            },
          ])
        }
      }
      if (type.column.key == 'excessWorkRate') {
        if (type.value) {
          this.$refs.processTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                excessWorkRate: fourFloatNum(type.value),
              },
            },
          ])
        }
      }
    },
    // 选择流程工序事件-------end
    treeChange(value, label, extra) {
      console.log('value:',value);
      console.log('label:',label);
      console.log('extra:',extra);
    },
    // 格式化超量报工
    inputRate(e) {
      this.form.setFieldsValue({
        excessWorkRate: clearNoNum(e.target.value),
      })
    },
    /* 超量报工校验大于0 */
    validateToRate(rule, value, callback) {
      if (!value) {
        callback()
      }
      if (/[1-9]+[0-9]*/.test(value)) {
        callback()
      } else {
        callback('超量报工必须大于0')
      }
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_PRODUCT_FLOW' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            flowCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 获取编辑详情 */
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this));
      this.queryId = id
      this.jkeForm.visible = true
      this.getdata()
      if (id) {
        this.jkeForm.title = '编辑流程'
        this.submitApi = messProductFlowEdit
        this.isEdit = true
        messProductFlowQueryById({ id: id }).then((res) => {
          if (res.code == 200) {
            let formObj = res.result
            formObj.goodsCategory = formObj.goodsCategory ? formObj.goodsCategory.split(',').map(item => {
              return { value: item }
            }) : []
            this.form.setFieldsValue(res.result)
            this.attachment = res.result.attachment
            this.processTable.dataSource = res.result.flowProcessRelVoList.map((item) => {
              item.processCodeName = `${item.processCode}-${item.processName} `
              return item
            })
          }
        })
      } else {
        this.jkeForm.title = '新建流程'
        this.form.setFieldsValue({
          status: 'enable',
        })
      }
    },
    getdata() {
      // 报工单位下拉字典数据
      getDictModel({ dictCode: 'wms_goods_unit' }).then((res) => {
        this.dictOptions = res.result
      })
      categoryGetTree({ code: 'B05' }).then((res) => {
        let arr = res.result
        let values = []
        arr[0].disabled = true
        if (!this.queryId) {
          arr.forEach((item) => {
            if (item.children.length > 0) {
              ;(function bianli(e = item) {
                e.children.forEach((chl) => {
                  values.push({
                    label: chl.name,
                    value: chl.id
                  })
                  if (chl.children.length > 0) {
                    bianli(chl)
                  }
                })
              })()
            }
          })
          this.form.setFieldsValue({
            goodsCategory: values
          })
        }
        this.treeData = arr
      })
      // 字典接口
      getDictModel({ dictCode: 'wms_goods_unit' }).then((res) => {
        this.dictOptionsGoodsUnit = res.result
        this.processTable.columns[3].options = res.result
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交
    handleSubmit() {
      this.form.validateFields((err, values) => {
        console.log(values, 'values form')
        if (!err) {
          let tableValue = this.$refs.processTable.getValuesSync({ validate: true })
          console.log(tableValue.error, tableValue.values,'error, values');
          if (tableValue.error === 0) {
            if (tableValue.values.length === 0) {
              this.$antdMessage.warning('工序不能为空')
              return
            }
          } else {
            return
          }
          let parameters = {
            ...values,
            attachment: this.attachment,
          }
          parameters.goodsCategory = parameters.goodsCategory.map((gc) => {
            return gc.value
          }).join(',')
          let flowProcessRelDtoList = tableValue.values.map((tv, j) => {
            tv.serialNo = j + 1
            return tv
          })
          parameters.flowProcessRelDtoList = flowProcessRelDtoList
          console.log(parameters, 'parameters')
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          this.loadingSubmit = true
          this.submitApi(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              let subMsg = this.isEdit ? '流程编辑成功！' : '流程创建成功！'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>
